#pragma once
#include <iostream>
#include <arpa/inet.h>
#include <sys/types.h>          
#include <sys/socket.h>
#include "InetAddr.hpp"
#include"log.hpp"
#include <unistd.h>
#include <netinet/in.h>




class Command
{
public:
	Command()
	{
	};
	void Handler(int sockfd,InetAddr Client)
        {
                while(true)//长服务
                {
                        char commandbuf[1024];//字节流当字符串使用
                        ssize_t n =read(sockfd,commandbuf,sizeof(commandbuf)-1);
                        if(n>0)
                        {
                                commandbuf[n] = 0;//恢复字符串
                                LOG(INFO, "get message from client %s, command: %s\n", Client.AddrStr().c_str(), commandbuf);
                                string result = Execute(commandbuf);
                               
                                write(sockfd,result.c_str(),result.size());
                        }
                        else if(n==0)
                        {
                                LOG(INFO, "client %s quit\n", Client.AddrStr().c_str());
                                break;
                        }
                        else
                        {
                                 LOG(ERROR, "read error: %s\n", Client.AddrStr().c_str());
                                break;
                        };

                };
                close(sockfd);
	}
	std::string Execute(const std::string& command)
	{
		//这里可以对命令进行筛选处理等操作
		FILE* fp =popen(command.c_str(),"r");
		if(fp)
		{
			std::string result;
			char line[1024];
			while(fgets(line,sizeof(line),fp))
			{
				result+=line;
			};
			return result.empty()?"success":result;

		};
		fclose(fp);
		return "Execute err";
	};



private:


};
